<?php

/**
 * SQLReslt
 *
 * @version $Id$
 * @copyright 2010
 */

/**
 * SQLResult
 *Class for iter SQLResult
 */
class SQLReslut extends sqld implements Iterator, ArrayAccess {
	protected $row;
	protected $primaryKey;
	protected $table;
	protected $position;
	protected $keysIndex;

	protected function makeIndex()
	{
		if ($this->primaryKey !== false)
		{
			$this->keysIndex = array();
			foreach ($this->row as $key => $value){
				$this->keysIndex[$value[$this->primaryKey]] = $key;
			}
		}
	}

	/**
	 * Constructor
	 */
	function __construct($rowtable, $primaryKey, $table){
		$this->row = $rowtable;
		$this->primaryKey = $primaryKey;
		$this->table = $table;
		$this->position = 0;

		$this->makeIndex();
	}
	
	function toArray()
	{
		return $this->row;
	}
	
	function count()
	{
		return count($this->row);
	}

	function  current()
	{
		if ($this->valid())
		{
			return new SQLRow($this->row[$this->position], $this->primaryKey, $this->table);
		}
		else
			return false;
	}

	function next()
	{
		$this->position++;
	}

	function key()
	{
		if ($this->primaryKey !== false)
		{
			return $this->row[$this->position][$this->primaryKey];
		}
		else
		{
			return $this->position;
		}
	}

	function rewind()
	{
		$this->position = 0;
	}

	function valid()
	{
		return isset($this->row[$this->position]);
	}

	function offsetExists($offset)
	{
		if ($this->primaryKey === false)
		{
			return false;
		}
		else
		{
			return isset($this->keysIndex[$offset]) && $this->row[$this->keysIndex[$offset]] !== null;
		}
	}

	function offsetGet($offset)
	{
		if ((is_integer($offset) || is_int($offset)) && $offset < $this->count())
		{
			return new SQLRow($this->row[$offset], $this->primaryKey, $this->table);
		}
		elseif (!$this->offsetExists($offset))
		{
			throw new Exception('offset not defined');
		}
		else
		{
			return new SQLRow($this->row[$this->keysIndex[$offset]], $this->primaryKey, $this->table);
		}
	}

	function offsetSet($offset, $value)
	{
		if (!$this->offsetExists($offset))
		{
			throw new Exception('Unknow key, this value don\'t exist.');
		}
		elseif (!$this->offsetExists($offset))
		{
			throw new Exception('offset not defined');
		}
		elseif (!is_array('value'))
		{
			throw new Exception('Invalid Arg');
		}
		else
		{
			$Query = 'UPDATE ' . $this->table . 'SET';
			foreach ($value as $Key => $Value){
				$value = $this->escape($value);
				$Query . ' `' . $Key . '`=\'' . $value . '\',';
			}
			$Query = substr($Query, 0, -1);
			$Query . ' WHERE `' . $this->primaryKey . '`'
				. '=\'' . $this->row[$this->keysIndex[$offset]][$this->primaryKey] . '\'';
			$this->query($Query);
			return $this->nbRow();
		}
	}

	function offsetUnset($offset)
	{
		if ($this->offsetExists($offset))
		{
			$this->row[$this->keysIndex[$offset]] = null;
		}
	}
}
?>